const router = require("koa-router")();
let fs = require("fs");
let permission_util = require("../util/permission_util");
let strings = require("../strings");
let path = require("path")


let initRouter = dir => {
  let files = fs.readdirSync(path.join(__dirname, "../" + dir));
  files.forEach(file => {
    if (file.endsWith(".js")) {
      let controllers = require("../" + dir + "/" + file);
      controllers.forEach(controller => {
        bindController(controller);
      });
    } else {
      initRouter(dir + "/" + file);
    }
  });
};

let bindController = controller => {
  console.log(`start ${controller.method.toLowerCase()} ${controller.path}`);
  if (controller.method.toLowerCase() == "get") {
    router.get(controller.path, async (ctx, next) => {
      return controllerHandle(ctx, next, controller);
    });
  } else {
    router.post(controller.path, async (ctx, next) => {
      console.log("post content");
      console.log(ctx.request.body);
      return controllerHandle(ctx, next, controller);
    });
  }
};

let controllerHandle = async (ctx, next, controller) => {
  let checked = await permission_util.checkPermission(
    ctx.request.body.token || ctx.request.query.token,
    controller
  );

  if (checked.check) {
    return controller.callback(ctx, next);
  } else {
    if (checked.message == strings.not_login) {
      return {
        success: false,
        code: "notlogin",
        message: checked.message
      };
    } else {
      ctx.throw(403, {
        message: checked.message
      });
    }
  }
};

initRouter("controller");

module.exports = router;
